# 处理带有依赖关系的序列（时间）的数据
# 自然语言有序列关系
# RNNcell and RNN
# demo of sequence to sequence:
import torch
import torch.nn as nn
import torch.optim as optim

input_size = 4
hidden_size = 4
batch_size = 1

idx2char = ['e', 'h', 'l', 'o']
x_data = [1, 0, 2, 2, 3]
y_data = [3, 1, 2, 3, 2]
one_hot_look_up = [
    [1, 0, 0, 0],
    [0, 1, 0, 0],
    [0, 0, 1, 0],
    [0, 0, 0, 1]
]
x_one_hot = [one_hot_look_up[x] for x in x_data]
inputs = torch.Tensor(x_one_hot).view(-1, batch_size, input_size)
labels = torch.LongTensor(y_data).view(-1, 1)


class rnnCell(nn.Module):
    def __init__(self, input_size, hidden_size, batch_size):
        super(rnnCell, self).__init__()
        self.batch_size = batch_size
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.rnnCell = torch.nn.RNNCell(input_size=self.input_size, hidden_size=self.hidden_size)

    def forward(self, input, hidden):
        hidden = self.rnnCell(input, hidden)
        return hidden

    def init_hidden(self):
        return torch.zeros(self.batch_size, self.hidden_size)


net = rnnCell(input_size, hidden_size, batch_size)

criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=0.01)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
net.to(device)
print(f'使用设备:{device}')

for epoch in range(100):
    loss = 0
    optimizer.zero_grad()
    hidden = net.init_hidden()
    print('predict string:', end='')
    for input, label in zip(inputs, labels):
        inputs,hidden=inputs.to(device), hidden.to(device)
        hidden = net(input, hidden)
        loss += criterion(hidden, label)
        _, idx = hidden.max(dim=1)
        print(idx2char[idx.item()], end='')
    loss.backward()
    optimizer.step()
    print('  epoch [%d/100] loss=%.4f' % (epoch + 1, loss.item()))
